import BaseCommonPresenter from "../.gen/presenter/component/common/CommonPresenter";

export default class CommonPresenter extends BaseCommonPresenter {

    treeToList(tree, list) {
        if (tree.length === 0) {
            return list;
        }
        tree.forEach((v) => {
            let {children} = v;
            let _v = {...v, children: null};
            delete _v.children;
            list.push(_v);
            if (children instanceof Array) {
                this.treeToList(children, list);
            }
        });
    }

    /**
     * @param body: {parentMenuId,sortToTree}
     * @returns Promise
     */
    findUserMenu(body, success, fails) {
        super.findUserMenu(body, (result) => {
            let list = result.data || [];
            if (list.length > 0) {
                let rootList = [];
                let _dataMap = {};
                list.forEach((m) => {
                    let {menuId} = m;
                    _dataMap[menuId] = m;
                });
                list.forEach((m) => {
                    let {parentMenuId} = m;
                    if (parentMenuId) {
                        let pM = _dataMap[parentMenuId];
                        if (pM) {
                            if (!pM.children) {
                                pM.children = [];
                            }
                            pM.children.push(m);
                        }
                    } else {
                        rootList.push(m);
                    }
                });
                if (rootList.length > 0) {
                    list = [];
                    this.treeToList(rootList, list);
                }
            }
            success(list);
        }, fails);
    }
}
